import React from 'react';
import { history } from 'umi'
import ReactEcharts from '@/components/Echarts';

const JobPie = ({ data = [], query = {} }) => {
    // 如果数据过多，则只保留前六位，剩余归到其他
    const filteredData = React.useMemo(() => {
        const sortedData = data.sort((a, b) => b.num - a.num);
        let sum = 0;
        return sortedData.reduce((prev, cur, i) => {
            if (i < 6) {
                return [...prev, cur];
            }
            const final = [...prev];
            sum += cur.num;
            final[6] = { name: '其他', num: sum };
            return final;
        }, []);
    }, [data]);

    const finalLegend = filteredData.map(item => item.name);
    const finalData = filteredData.map(item => ({ value: item.num, name: item.name }));
    const handleChartClick = () => {
        history.push({ pathname: '/stat/workStat/workOverview/work/employee', query });
    };

    return (
        <ReactEcharts
            onEvents={{ click: handleChartClick }}
            option={{
                color: ['#FFA808', '#4DCB73', '#36CBCB', '#F2637B', '#975FE4', '#7191F8', '#5D7092'],
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                legend: {
                    right: 0,
                    top: 0,
                    orient: 'vertical',
                    data: finalLegend
                },
                series: [
                    {
                        name: '',
                        type: 'pie',
                        radius: ['50%', '70%'],
                        center: ['38%', '50%'],
                        data: finalData,
                        itemStyle: {
                            normal: {
                                borderWidth: 2,
                                borderColor: '#ffffff'
                            },
                            emphasis: {
                                borderWidth: 0,
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    }
                ]
            }}
        />
    );
};

export default JobPie;
